using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.UserControls;
using SE.HTMLRepeater.Components;

namespace SE.HTMLRepeater
{
    public partial class Edit:  PortalModuleBase
    {

        int itemId = Null.NullInteger;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                List<DisplayVar> variables = new List<DisplayVar>();
        
                if (Request.QueryString["ItemId"] != null)
                {
                    itemId = Int32.Parse(Request.QueryString["ItemId"]);
                }

                if (!IsPostBack)
                {
                    //load the data into the control the first time
                    //we hit this page


                    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") +"');");
                    string template = Util.getTemplate(this);
                    List<string> templateItems = Util.GetTemplateItems(template);


                    //check we have an item to lookup
                    HTMLRepeaterController controller = new HTMLRepeaterController();
                    if (!Null.IsNull(itemId))
                    {
                        //load the item
                        
                        HTMLRepeaterInfo item = controller.GetHTMLRepeater(this.ModuleId, itemId);

                        if (item != null)
                        {
                            txOrder.Text = item.DisplayOrder.ToString();
                            txAnchorName.Text = item.AnchorText;
                            variables =Util.DecompressVariables(item.Content,templateItems);
                            
                            ctlAudit.CreatedByUser = item.CreatedByUserName;
                            ctlAudit.CreatedDate = item.CreatedDate.ToLongDateString();
                        }
                        else

                            Response.Redirect(Globals.NavigateURL(), true);
                    }
                    else
                    {
                        if (controller.GetHTMLRepeatersCount(ModuleId) > 0)
                            txOrder.Text = controller.GetNextOrder(this.ModuleId).ToString();
                        else
                        {
                            txOrder.Text = "0";
                        }
                    	variables = CreateNewEntryForm(templateItems);
                    	cmdDelete.Visible = false;
                    	ctlAudit.Visible = false;
						
                    }
                }

                rptrVariables.DataSource = variables;
                rptrVariables.DataBind();
            }
            catch(Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        protected void RptrItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DisplayVar Dv = (DisplayVar) e.Item.DataItem;
                Label theLabel = (Label) e.Item.FindControl("lblVariable");
                PlaceHolder theVariable = (PlaceHolder) e.Item.FindControl("plhVariable");
                System.Web.UI.Control theControl = null;
                if(Dv.VarName.IndexOf('*') > -1)
                {
                    theControl = new TextBox();
                    ((TextBox)theControl).TextMode = TextBoxMode.MultiLine;
                    ((TextBox)theControl).Height = 100;
                    ((TextBox)theControl).Width = 400;
                    theLabel.Text = Dv.VarName.Replace(@"*", @"");
                    ((TextBox)theControl).Text = Dv.VarValue;
                }
                //else if (Dv.VarName.IndexOf('\\') > -1)
                //{
                //    theControl = new DotNetNuke.UI.UserControls.UrlControl();

                //    theLabel.Text = Dv.VarName.Replace(@"\", @"");
                //}
                else
                {
                    theControl = new TextBox();
                    ((TextBox)theControl).TextMode = TextBoxMode.SingleLine;
                    ((TextBox)theControl).Width = 150;
                    ((TextBox)theControl).Text = Dv.VarValue;
                    theLabel.Text = Dv.VarName;
                }

                theControl.ID = Dv.VarName + ":" + theVariable.ID; //rename so we can find the name of the variable in the form postback.
                theVariable.Controls.Add(theControl);
            }
        }
        
        private List<DisplayVar> CreateNewEntryForm(List<string> templateItems)
        {
            List<DisplayVar> DVs = new List<DisplayVar>();
            foreach (string s in templateItems)
            {
                DisplayVar displayVar = new DisplayVar(s,"");

                DisplayVar dV = DVs.Find(dv => dv.VarName == displayVar.VarName); //predicate short hand search.
                
                if (dV ==null)
                {DVs.Add(displayVar);}
            }
            return DVs;
        }


        private string CompressVariables(out int order, out string anchorText)
        {
            string Variables = "";
            order = 0; // have to set default.
            anchorText = "";
            foreach (string key in this.Request.Form.AllKeys)
            {
                //check the key name and then get the var if it fits.
                if (key.EndsWith("plhVariable"))
                {
                    int iStart = key.LastIndexOf('$');
                    int iEnd = key.IndexOf(':', iStart + 1);
                    string VarName = key.Substring(iStart + 1, (iEnd - iStart) - 1);
                    //do somthing.
                    if (!VarName.StartsWith("!~")) //Old value removed.
                    {
                        if (Variables.Length != 0)
                        {
                            Variables += "`,`";
                        }
                        Variables += VarName + "`~`" + Request.Form[key].ToString();
                    }
                }
                else if (key.EndsWith("txOrder"))
                {
                    order = Convert.ToInt32("0" + Request.Form[key].ToString());
                }
                else if (key.EndsWith("txAnchorName"))
                {
                    anchorText = Request.Form[key].ToString();
                }
            }

            return Variables;
        }


        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                HTMLRepeaterController controller = new HTMLRepeaterController();
                HTMLRepeaterInfo item = new HTMLRepeaterInfo();
                int itemOrder = 0;
                string anchorText = "";
                item.Content = CompressVariables(out itemOrder,out anchorText);
                item.ItemId = itemId;
                item.ModuleId = this.ModuleId;
                item.CreatedByUser = this.UserId;
                item.DisplayOrder = itemOrder;
                item.AnchorText = anchorText;

                //determine if we are adding or updating
                if (Null.IsNull(item.ItemId))
                    controller.AddHTMLRepeater(item);
                else
                    controller.UpdateHTMLRepeater(item);

                Response.Redirect(Globals.NavigateURL(), false);
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Globals.NavigateURL(), false);
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Null.IsNull(itemId))
                {
                    HTMLRepeaterController controller = new HTMLRepeaterController();
                    controller.DeleteHTMLRepeater(this.ModuleId, itemId);
                    Response.Redirect(Globals.NavigateURL(), false);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
    }
}